---
import { Card, Heading, Link } from 'accessible-astro-components'
import { Icon } from 'astro-icon/components'

// Import images directly for optimization
import postImage1 from '@assets/images/posts/post-image-1.png'
import postImage2 from '@assets/images/posts/post-image-2.png'
import postImage3 from '@assets/images/posts/post-image-3.png'

/**
 * FeaturedPosts Component
 *
 * @description A component that displays featured blog posts from JSONPlaceholder API
 */
interface Props {
  /**
   * Additional classes to apply to the section
   */
  class?: string
  /**
   * The number of posts to display
   * @default 3
   */
  limit?: number
  /**
   * The title for the section
   * @default "Latest posts"
   */
  title?: string
}

interface Post {
  id: number
  userId: number
  title: string
  body: string
  featuredImage: any
  shortUrl: string
}

const { class: className, limit = 3, title = 'Latest posts' } = Astro.props

// Fetch posts from API
const response = await fetch('https://jsonplaceholder.typicode.com/posts')
const data = await response.json()

const postImages = [postImage1, postImage2, postImage3]

// Function to truncate title for better display
function truncateTitle(title: string): string {
  const words = title.split(' ')
  const truncated = words.slice(0, 4).join(' ')
  return truncated
}

// Process and limit posts for featured section
const featuredPosts: Post[] = data.slice(0, limit).map((post: any) => {
  const truncatedTitle = truncateTitle(post.title)
  return {
    ...post,
    featuredImage: postImages[post.id % postImages.length],
    title: truncatedTitle,
    shortUrl: truncatedTitle.replaceAll(' ', '-').toLowerCase(),
  }
})
---

<section class:list={[className, 'my-64']}>
  <div class="container">
    <Heading level="h2" class="mb-6">{title}</Heading>
    <div class="grid grid-cols-1 gap-12 md:grid-cols-2 lg:grid-cols-3">
      {
        featuredPosts.map((post) => (
          <Card
            imageComponent={post.featuredImage}
            url={'/blog/' + post.shortUrl}
            headingLevel="h2"
            title={post.title}
            footer={'User ID: ' + post.userId}
          >
            {post.body}
          </Card>
        ))
      }
    </div>
    <div class="mt-12">
      <Link href="/blog/" isButton animateOnHover animationType="nudge">
        Read all posts
        <Icon aria-hidden="true" name="lucide:arrow-right" size="1.5rem" />
      </Link>
    </div>
  </div>
</section>
